package com.comum.javahomework420242025.controller;
import com.comum.javahomework420242025.mapper.UserMapper;
import com.comum.javahomework420242025.pojo.*;
import com.comum.javahomework420242025.repository.AreaRepository;
import com.comum.javahomework420242025.repository.ChanceRepository;
import com.comum.javahomework420242025.repository.UserRepository;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChanceRepository chanceRepository;

    @GetMapping("/getUser")
    public Result<User> getUser(HttpServletRequest req){
        HttpSession session = req.getSession();
        Long id = (Long) session.getAttribute("userid");
        Optional<User> optionaluser = userRepository.findById(id);
        User user = optionaluser.get();
        return Result.success(user);
    }
    @PostMapping ("/addUser")
    public Result addUser(@RequestBody User user){
        user.setId(null);
        System.out.println(user);
        Long accountnumber = System.currentTimeMillis();
        String account = accountnumber.toString();
        String pass = "123456";
        user.setAccount(account);
        user.setPass(pass);
        userRepository.save(user);
        return Result.success();
    }

    @PutMapping ("/updateUser")
    public Result updateUser(@RequestBody User user){
        System.out.println(user);
        userRepository.save(user);
        return Result.success();
    }

    @PostMapping("/getUser")
    public Result<PageBean<User>> getUser(@RequestBody AskList askList){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        PageBean<User> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<User> page = userRepository.selectByStr(str,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        return Result.success(pb);
    }

    @PostMapping("/moveUser")
    public Result moveUser(String areaid,@RequestBody List<User> users){
        for(int i=0;i<users.size();i++){
            users.get(i).setAreaid(Long.valueOf(areaid));
            users.get(i).setAreaname(null);
            userRepository.save(users.get(i));
        }
        return Result.success();
    }
    @PostMapping("/movegetUser")
    public Result<PageBean<User>> movegetUser(@RequestBody AskList askList){
        PageBean<User> pb = new PageBean<>();
        int pageNum = askList.getPageNum();
        int pageSize = askList.getPageSize();
        String areaid = askList.getAreaid();
        String department = askList.getDepartment();
        String str = askList.getStr();
        //开启分页查询 ,PageHelper是个插件
        PageHelper.startPage(pageNum,pageSize);
        List<User> as = userMapper.listpart(areaid,department,str);
        System.out.println(as.size());
        //Page中提供了方法，可以获取PageHelper分页查询后  得到的总记录条数和当前页数据
        com.github.pagehelper.Page<User> p = (com.github.pagehelper.Page<User>) as;
        //把数据填充到PageBean对象中
        List<User> users = p.getResult();
        System.out.println(users);
        pb.setItems(users);
        pb.setTotal(p.getTotal());
        System.out.println(pb);
        return Result.success(pb);
    }

    @DeleteMapping("/deleteUser")
    public Result deleteUser(String id){
        List<Chance> res = chanceRepository.findByUserId(id);
        if(res.size()!=0){
            return Result.error("该用户关联其他信息，无法删除！");
        }
        userRepository.deleteById(Long.valueOf(id));
        return Result.success();
    }
    @GetMapping("/getAllUserForClientComeAdd")
    public Result<List<UserForResult>>getAllUserForClientComeAdd(){
        List<UserForResult> users = userMapper.findAllUserNameAndDepartment();
        System.out.println(users);
        return Result.success(users);
    }
    @GetMapping("/getAllUser")
    public Result getAllUser()
    {
        return Result.success(userRepository.findAll());
    }

    @PostMapping("/getAllAreaMaster")
    public Result getAllAreaMaster(@RequestBody AskList askList)
    {

        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        PageBean<User> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<User> page = userRepository.findALLByType("片区负责人", pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());

        return Result.success(pb);
    }

    @PostMapping("/getAllNotAreaMaster")
    public Result getAllNotAreaMaster(@RequestBody AskList askList)
    {

        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        PageBean<User> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<User> page = userRepository.findALLByType("销售员工", pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());

        return Result.success(pb);
    }

    @PostMapping("/getAllAreaMasterNotChoose")
    public Result getAllAreaMasterNotChoose(@RequestBody AskList askList)
    {

        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        PageBean<User> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<User> page = userRepository.getAllAreaMasterNotChoose("片区负责人", str, pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());

        return Result.success(pb);

    }

    @PostMapping("/getAllNotAreaMasterNotChoose")
    public Result getAllNotAreaMasterNotChoose(@RequestBody AskList askList)
    {

        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        PageBean<User> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<User> page = userRepository.getAllAreaMasterNotChoose("销售员工", str, pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());

        return Result.success(pb);

    }

    @PostMapping("/getUserByType")
    public Result getUserByType(@RequestBody AskList askList)
    {
        String str = askList.getStr();
        List<User> users = userRepository.findUserBYTyoe(str);
        return Result.success(users);
    }


    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Password password){
        //1.校验参数
        String oldPwd = password.getOldPassword();
        String newPwd =  password.getNewPassword();
        String rePwd =  password.getRePassword();




        Optional<User> loginuser = userRepository.findById(password.getId());
        System.out.println("loginuser.get().getPass()" + loginuser.get().getPass());
        System.out.println("newPwd:"+newPwd);
        if(!loginuser.get().getPass().equals(oldPwd)){
            return Result.error("原密码填写不正确");
        }
        //newPwd和rePwd是否一样
        if (!newPwd.equals(rePwd)) return Result.error("确认密码和新密码不同");
        loginuser.get().setPass(newPwd);
        userRepository.save(loginuser.get());
        //删除redis中对应的token
        return Result.success();
    }

}
